// pages/shopDetail/shopDetail.js
var app = getApp();
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: app.globalData.isIphoneX,
    fromPage: '', // 页面来源
    goodsId: "", // 商品id
    detail: {}, // 商品信息
    commenDetail: {}, // 评论详情
    goodsCount: 1, // 商品数量
    selectFlag: 0, // 商品类别选择
    risk: '', // 风险提示
    show: false, // 购买弹框
    show1: false, // 分享弹框
    shareImg: '', // 分享图片
    show2: false, // 保存图片
    show3: false, // 商品规格
    show4: false, // 评价
    show5: false, // 放大图片
    star: 0, // 评论星星
    remark: '', // 评论内容
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log('==== options ====', options)
    // options.id = 1030001
    if (options.scene) {
      console.info('==== scene ====',decodeURIComponent(options.scene))
      options.id = decodeURIComponent(options.scene).split('&')[0]
      options.userId = decodeURIComponent(options.scene).split('&')[1]
      options.grouponNo = decodeURIComponent(options.scene).split('&')[2]
      console.log('==== options ====', options)
    }
    if (options.fromPage) {
      this.setData({
        fromPage: options.fromPage
      })
    }
    this.setData({
      goodsId: options.id,
      userId: options.userId,
      grouponNo: options.grouponNo
    })
  },
  
  // 选择回报选择
  tabClick(e) {
    console.log(e)
    this.setData({
      selectFlag: e.currentTarget.dataset['index']
    })
  },

  toShopCar() {
    wx.navigateTo({
      url: '/pages/shopCar/shopCar',
    })
  },

  // 增加数量
  addCount() {
    this.setData({
      goodsCount: this.data.goodsCount + 1
    })
    if (this.data.goodsCount > 99) {
      this.setData({
        goodsCount : 99
      })
    }
  },

  // 减少数量
  subCount() {
    if (this.data.goodsCount > 1) {
      this.setData({
        goodsCount: this.data.goodsCount - 1
      })
    }
  },

  bindKeyInput(e) {
    let reg = /^([1-9]\d|\d)$/
    console.log(e.detail.value, reg.test(e.detail.value))
    if (reg.test(e.detail.value)) {
      if (e.detail.value < 1) {
        this.setData({
          goodsCount : 1
        })
      } else if (e.detail.value > 99) {
        this.setData({
          goodsCount : 99
        })
      } else {
        this.setData({
          goodsCount : e.detail.value
        })
      }
    } else {
      if(e.detail.value.length > 1) {
        this.setData({
          goodsCount : '99'
        })
      } else {
        this.setData({
          goodsCount : ''
        })
      }
    }
  },

  bindKeyBlur(e) {
    if (!this.data.goodsCount) {
      this.setData({
        goodsCount: '1'
      })
    }
    if (this.data.goodsCount < 10) {
      this.setData({
        cursorFlag: 0
      })
    }
  },

  // 添加购物车
  addShopCar() {
    let params = {
      goodsId: this.data.detail.goodsProd[this.data.selectFlag].goodsId,
      productId: this.data.detail.goodsProd[this.data.selectFlag].id,
      goodsSn: this.data.detail.goodsSn,
      number: this.data.goodsCount,
      grouponNo: this.data.grouponNo,
      shareUserId: this.data.userId
    }
    console.info(params)
    wx.post(wx.api.carAdd, params, res=> {
      console.info('=== carAdd ====', res)
      if (res.code == 200) {
        this.setData({
          show: false
        })
        wx.showToast({
          title: '添加购物车成功',
          icon: 'none',
          duration: 1000
        })
      }
    })
  },

  // 跳转确认订单
  toOrderConfirm() {
    console.info('666')
    if (this.data.detail.goodsProd[this.data.selectFlag].number<=0) {
      return
    }
    let that = this
    wx.setStorage({
      key:"shopDetail",
      data: [{
        goodsName: this.data.detail.name,
        goodsId: this.data.detail.goodsProd[this.data.selectFlag].goodsId,
        productId: this.data.detail.goodsProd[this.data.selectFlag].id,
        number: this.data.goodsCount,
        price: this.data.detail.goodsProd[this.data.selectFlag].price,
        goodsProductName: this.data.detail.goodsProd[this.data.selectFlag].specifications,
        shareUserId: this.data.userId,
        grouponNo: this.data.grouponNo,
        goodsUrl: this.data.detail.goodsProd[this.data.selectFlag].url
      }],
      success() {
        that.setData({
          show: false
        })
        wx.navigateTo({
          url: '/pages/shopOrderConfirm/orderConfirm'
        })
      }
    })
  },

  // 跳转协议
  jumpAgree(e) {
    let url
    if (e.currentTarget.dataset.type == 1) {
      url = encodeURIComponent(app.globalData.host+'/doc/refund.html')
      wx.navigateTo({
        url: `/pages/webview/webview?url= ${url}`,
      })
    } else {
      
    }
  },

  // 跳转问卷
  toWenQuan() {
    wx.navigateTo({
      url: '/pages/wenjuan/wenjuan',
    })
  },

  // 跳转评论
  toComment() {
    wx.navigateTo({
      url: `/pages/comment/comment?goodsId=${this.data.goodsId}`,
    })
  },

  // 分享
  share(e) {
    let api = '/api/goods/'
    if (e.currentTarget.dataset.type == 'link') {
      api += `shareUrl?goodsId=${this.data.goodsId}`
    } else if (e.currentTarget.dataset.type == 'link_wb') {
      api += `shareUrl?goodsId=${this.data.goodsId}&urlType=1`
    } else {
      api += `shareImage?goodsId=${this.data.goodsId}`
    }
    wx.get(api, res => {
      console.log(e.currentTarget.dataset.type, res)
      if (res.code == 200) {
        if (e.currentTarget.dataset.type == 'link' || e.currentTarget.dataset.type == 'link_wb') {
          wx.setClipboardData({
            data: res.data.shareUrl,
            success (_res) {
              wx.getClipboardData({
                success (__res) {
                  console.log(__res.data) // data
                }
              })
            }
          })
        } else {
          wx.showLoading({
            mask: true
          })
          this.setData({
            shareImg: res.data.shareImg,
            show2: true,
            show1: false
          })
        }
      }
    }, fail => {})
  },

  imageLoad() {
    console.info('==== 图片加载完成 ====')
    wx.hideLoading()
  },

  // 保存图片
  save() {
    let that = this
    wx.showLoading({
      mask: true
    })
    wx.getImageInfo({
      src:  that.data.shareImg,
      success (ress) {
        console.log(ress)
        wx.saveImageToPhotosAlbum({
          filePath: ress.path,
          success(res) {
            wx.hideLoading()
            that.setData({
              show2: false
            })
            wx.showToast({
              title: '图片保存成功',
              icon: 'none',
              duration: 2000
            })
          }
        })
      }
    })
    
  },

  showPopup() {
    this.setData({ show: true });
  },

  onClose() {
    this.setData({ show: false });
  },

  showPopup1() {
    this.setData({ show1: true });
  },

  onClose1() {
    this.setData({ show1: false });
  },

  showPopup2() {
    this.setData({ show2: true });
  },

  showPopup3() {
    this.setData({ show3: true });
  },

  onClose2() {
    this.setData({ show2: false });
  },

  onClose3() {
    this.setData({ show3: false });
  },

  showPopup4() {
    this.setData({ show4: true });
  },

  onClose4() {
    this.setData({ show4: false });
  },

  showPopup5() {
    this.setData({ show5: true });
  },

  onClose5() {
    this.setData({ show5: false });
  },

  toStar(e) {
    console.info(e.currentTarget.dataset.star)
    this.setData({
      star: e.currentTarget.dataset.star + 1
    })
  },

  bindKeyInput: function (e) {
    this.setData({
      [e.target.dataset.name]: e.detail.value
    })
  },

  // 评价订单
  commentOrder() {
    let params = {
      // orderId: commentItem.id,
      goodsId: this.data.goodsId,
      star: this.data.star,
      content: this.data.remark,
      type: 1,
    }
    console.info(params)
    wx.post(wx.api.commentAdd, params, res => {
      if (res.code == 200) {
        this.setData({
          show4: false
        })
        this.getDetail()
      }
    })
  },
  
  showSenven() {
    wx.get('/api/config/configKey?key=7day_return', res => {
        if (res.code == 200) {
            Dialog.alert({
              title: '温馨提示',
              message: res.msg,
              confirmButtonText: '好的'
            })
        }
    })
  },

  // 返回页面顶部
  scrollTop() {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getDetail()
    wx.get('/api/comment/score?goodsId='+ this.data.goodsId, res => {
      console.log('==== comment ===', res)
      this.setData({
        commenDetail: res.data
      })
    }, fail => {})
  },

  getDetail() {
    wx.get("/api/goods/mallDetail?goodsId="+ this.data.goodsId, res => {
      console.log('==== detail ===', res)
      // 处理商品已购买价格
      res.data.totalAmount = (res.data.totalAmount*100 + res.data.dummyMoney*100)/100
      // 商品评论取两条
      res.data.goodsComment = res.data.goodsComment.slice(0, 2)
      // 处理商品图片富文本
      res.data.detail = res.data.detail.replace(/\/\>/gi, ' style="display:block" width="100%" height=""/>')
      // 处理商品类型 数组转成字符串
      res.data.goodsProd = res.data.goodsProd.map(item=> {
        return {...item, specificationsText: item.specifications.join('+')}
      })
      let goodsAttrText = ''
      res.data.goodsAttr.forEach((item, index) => {
        if (index == 0) {
          goodsAttrText += item.attribute
        } else {
          goodsAttrText += ' · ' + item.attribute
        }
      });
      res.data.goodsAttrText = goodsAttrText
      // 处理剩余天数 
      // let nowTime = new Date()*1
      // let endTime = new Date(res.data.endTime.replace(/-/g, '/'))*1
      // let endDay = Math.floor((endTime - nowTime) / (1000*3600*24))
      // res.data.endDay =  endDay > 0 ? endDay : 0
      this.setData({
        detail: res.data
      })
    }, fail => {})
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title:  this.data.detail.name,
      path: `/pages/shopDetail/shopDetail?id=${this.data.goodsId}`,
      imageUrl: this.data.detail.picUrl
    }
  },

   /**
   * 用户点击右上角分享转发到朋友圈
   */
  onShareTimeline() {
    return {
      title:  this.data.detail.name,
      query: `id=${this.data.goodsId}`,
      imageUrl: this.data.detail.picUrl
    }
  }
})